package com.dm;

import static com.dm.util.Constant.DIALOG_ALL_DEL_CONFIRM;
import static com.dm.util.Constant.DIALOG_SCH_DEL_CONFIRM;
import static com.dm.util.Constant.DIALOG_SCH_SYNC_CONFIRM;
import static com.dm.util.Constant.DIALOG_SET_DATETIME;
import static com.dm.util.Constant.DIALOG_SET_SEARCH_RANGE;
import static com.dm.util.Constant.getNowDateString;
import static com.dm.util.DBUtil.deletePassedSchedule;
import static com.dm.util.DBUtil.deleteSchedule;
import static com.dm.util.DBUtil.deleteType;
import static com.dm.util.DBUtil.getAllEventId;
import static com.dm.util.DBUtil.getAllType;
import static com.dm.util.DBUtil.insertSchedule;
import static com.dm.util.DBUtil.insertType;
import static com.dm.util.DBUtil.loadSchedule;
import static com.dm.util.DBUtil.loadType;
import static com.dm.util.DBUtil.searchSchedule;
import static com.dm.util.DBUtil.updateSchedule;

import java.util.ArrayList;
import java.util.Calendar;

import android.R.bool;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.Toast;

import com.dm.adapter.ListTypeAdapter;
import com.dm.adapter.ListViewAdapter;
import com.dm.adapter.SearchAdapter;
import com.dm.adapter.SpAlarmAdapter;
import com.dm.adapter.SpTypeAdapter;
import com.dm.bean.Schedule;
import com.dm.bean.SpAlarmItem;
import com.dm.util.CalendarUtil;
import com.dm.util.Constant.Layout;
import com.dm.util.Constant.WhoCall;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.google.ads.c;

@SuppressLint("ResourceAsColor")
public class DmActivity extends Activity {

    Context context;
    public static String[] defultType = new String[] { "備忘", "會議", "待辦" };// 軟件的三個不能刪除的默認類型
    Dialog dialogSetRange;// 日程查找時設置日期起始範圍的對話框
    Dialog dialogSetDatetime;// 新建或修改日程時設置日期和時間的對話框
    Dialog dialogSchDelConfirm;// 刪除日程時的確認對話框
    Dialog dialogSchSyncConfirm;// 同步日程時的確認對話框
    Dialog dialogCheck;// 主界面中查看日程詳細內容的對話框
    Dialog dialogAllDelConfirm;// 刪除全部過期日程時的確認對話框
    Dialog dialogDelType;// 刪除類型對話框
    public static CalendarUtil util;
    public static ArrayList<String> alType = new ArrayList<String>();// 存儲所有日程類型的arraylist
    public static ArrayList<String> alEventId = new ArrayList<String>();// 存儲所有日程類型的arraylist
    public static ArrayList<SpAlarmItem> alAlarm = new ArrayList<SpAlarmItem>();// 存儲所有日程類型的arraylist
    public static ArrayList<Schedule> alSch = new ArrayList<Schedule>();// 存儲所有schedule對象的ArrayList
    public Schedule schTemp;// 臨時的schedule
    public static String rangeFrom = getNowDateString();// 查找日程時設置的起始日期，默認當前日期
    public static String rangeTo = rangeFrom;// 查找日程時設置的終止日期，默認當前日期
    Layout curr = null;// 記錄當前界面的枚舉類型
    WhoCall wcSetTimeOrAlarm;// 用來判斷調用時間日期對話框的按鈕是設置時間還是設置鬧鐘,以便更改對話框中的一些控件該設置為visible還是gone
    public static WhoCall wcNewOrEdit;// 用來判斷調用日程編輯界面的是新建日程按鈕還是在修改日程按鈕，以便設置對應的界面標題
    int sel = 0;
    int sel2 = 0;
    private AdView adView;
    private AdRequest request;
    private boolean open = false;
    public static int currentPosition = -1;
    private Handler handler = new Handler() {

	public void handleMessage(android.os.Message msg) {
	    switch (msg.what) {
		case 1:
		    gotoSetting();
		    break;
		case 2:
		    showDialog(DIALOG_SCH_DEL_CONFIRM);
		    break;
		case 3:
		    Toast.makeText(context, "同步完成", Toast.LENGTH_LONG).show();
		    deletePassedSchedule(context);
		    gotoMain();
		    break;
		case 4:
		    Toast.makeText(context, "同步完成", Toast.LENGTH_LONG).show();
		    gotoMain();
		    break;
	    }
	}
    };

    /*
     * 臨時記錄新建日程界面裡的類型spinner的position，因為設置時間的對話框cancel後
     * 回到新建日程界面時會刷新所有控件，spinner中以選中的項目也會回到默認
     */
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	requestWindowFeature(Window.FEATURE_NO_TITLE);// 無標題
	context = this;
	addSpAlarmItem();
	request = new AdRequest();
	// request.addTestDevice(AdRequest.TEST_EMULATOR); // 所有仿真器
	// request.addTestDevice("3588CCA00A9815EF5C19EC506AF338FE");
	gotoMain();
    }

    private void addSpAlarmItem() {
	alAlarm.clear();
	alAlarm.add(new SpAlarmItem(0, "無提醒", "x"));
	alAlarm.add(new SpAlarmItem(1, "準時", "0"));
	alAlarm.add(new SpAlarmItem(2, "1分鐘", "1"));
	alAlarm.add(new SpAlarmItem(3, "5分鐘", "5"));
	alAlarm.add(new SpAlarmItem(4, "10分鐘", "10"));
	alAlarm.add(new SpAlarmItem(5, "15分鐘", "15"));
	alAlarm.add(new SpAlarmItem(6, "20分鐘", "20"));
	alAlarm.add(new SpAlarmItem(7, "25分鐘", "25"));
	alAlarm.add(new SpAlarmItem(8, "30分鐘", "30"));
	alAlarm.add(new SpAlarmItem(9, "45分鐘", "45"));
	alAlarm.add(new SpAlarmItem(10, "1小時", "60"));
	alAlarm.add(new SpAlarmItem(11, "2小時", "120"));
	alAlarm.add(new SpAlarmItem(12, "3小時", "180"));
	alAlarm.add(new SpAlarmItem(13, "6小時", "360"));
	alAlarm.add(new SpAlarmItem(14, "12小時", "720"));
	alAlarm.add(new SpAlarmItem(15, "24小時", "1440"));
	alAlarm.add(new SpAlarmItem(16, "2天", "2880"));
	alAlarm.add(new SpAlarmItem(17, "3天", "4320"));
	alAlarm.add(new SpAlarmItem(18, "1週", "10080"));
	alAlarm.add(new SpAlarmItem(19, "2週", "20160"));
    }

    // ===================================主界面start===========================================
    // 初始化主界面
    ImageButton ImNew, ImDelAll, ImSearch, ImSync;
    ListView lv;
    ListViewAdapter listViewAdapter;
    ArrayList<String> EventIdList;

    public void gotoMain() {
	getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
		WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
	setContentView(R.layout.main);
	curr = Layout.MAIN;
	sel = 0;
	if (util == null) {
	    util = new CalendarUtil(DmActivity.this);
	}
	ImNew = (ImageButton) findViewById(R.id.ibmainNew);// 新建日程按鈕
	ImDelAll = (ImageButton) findViewById(R.id.ibmainDelAll);// 刪除所有過期日程按鈕
	ImSearch = (ImageButton) findViewById(R.id.ibmainSearch);// 查找日程按鈕
	ImSync = (ImageButton) findViewById(R.id.ibmainSync);
	adView = (AdView) findViewById(R.id.adView);
	adView.loadAd(request);
	lv = (ListView) findViewById(R.id.lvmainSchedule);// 日程列表
	alSch.clear();// 從數據庫讀取之前清空存儲日程的arraylist
	loadSchedule(this);// 從數據庫中讀取日程
	loadType(this);// 從數據庫中讀取類型
	// 如果沒有任何日程，則刪除全部過期日程按鈕設為禁用
	if (alSch.size() == 0) {
	    ImDelAll.setEnabled(false);
	} else {
	    ImDelAll.setEnabled(true);
	}
	// 以下是ListView設置
	listViewAdapter = new ListViewAdapter(context, alSch, handler);
	lv.setAdapter(listViewAdapter);
	lv.setOnItemClickListener(new OnItemClickListener() {

	    @Override
	    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (!open) {
		    schTemp = alSch.get(position);
		    currentPosition = position;
		    open = true;
		} else if (currentPosition != position) {
		    schTemp = alSch.get(position);
		    currentPosition = position;
		    open = true;
		} else {
		    currentPosition = -1;
		    open = false;
		}
		listViewAdapter.notifyDataSetChanged();
	    }
	});
	ImNew.setOnClickListener(MainClickListener);// bNew設置
	ImDelAll.setOnClickListener(MainClickListener);// 刪除所有過期日程按鈕
	ImSearch.setOnClickListener(MainClickListener);// 日程查找按鈕
	ImSync.setOnClickListener(MainClickListener);
    }

    OnClickListener MainClickListener = new OnClickListener() {

	@Override
	public void onClick(View v) {
	    switch (v.getId()) {
		case R.id.ibmainNew:
		    Calendar c = Calendar.getInstance();
		    int t1 = c.get(Calendar.YEAR);
		    int t2 = c.get(Calendar.MONTH) + 1;
		    int t3 = c.get(Calendar.DAY_OF_MONTH);
		    schTemp = new Schedule(t1, t2, t3);// 臨時新建一個日程對象，年月日設為當前日期
		    wcNewOrEdit = WhoCall.NEW;// 調用日程編輯界面的是新建按鈕
		    gotoSetting();// 去日程編輯界面
		    break;
		case R.id.ibmainDelAll:
		    showDialog(DIALOG_ALL_DEL_CONFIRM);
		    break;
		case R.id.ibmainSearch:
		    gotoSearch();
		    break;
		case R.id.ibmainSync:
		    showDialog(DIALOG_SCH_SYNC_CONFIRM);
		    break;
	    }
	}
    };
    Spinner spType, spAlarm;
    EditText etTitle, etNote;
    Button bNewType, bSetDate, bDone, bCancel;
    TextView tvTitle, tvDate, tvTime, tvAlarm;
    SpTypeAdapter spTypeAdapter;
    SpAlarmAdapter spAlarmAdapter;

    // ===================================日程編輯界面start=====================================
    public void gotoSetting() {// 初始化新建日程界面
	setContentView(R.layout.newschedule);
	context = this;
	curr = Layout.SETTING;
	TextView tvTitle = (TextView) findViewById(R.id.tvnewscheduleTitle);
	if (wcNewOrEdit == WhoCall.NEW) {
	    tvTitle.setText("新建日程");
	    sel = 0;
	    sel2 = 0;
	} else if (wcNewOrEdit == WhoCall.EDIT) {
	    tvTitle.setText("修改日程");
	    String type = schTemp.getType();
	    for (int i = 0; i < alType.size(); i++) {
		if (type.equals(alType.get(i))) {
		    sel = i;
		}
	    }
	    String time2 = schTemp.getTime2();
	    for (int i = 0; i < alAlarm.size(); i++) {
		if (time2.equals(alAlarm.get(i).getValue())) {
		    sel2 = alAlarm.get(i).getId();
		}
	    }
	}
	spType = (Spinner) findViewById(R.id.spxjrcType);
	spAlarm = (Spinner) findViewById(R.id.spAlarm);
	bNewType = (Button) findViewById(R.id.bxjrcNewType);
	etTitle = (EditText) findViewById(R.id.etxjrcTitle);
	etNote = (EditText) findViewById(R.id.etxjrcNote);
	tvDate = (TextView) findViewById(R.id.tvnewscheduleDate);
	bSetDate = (Button) findViewById(R.id.bxjrcSetDate);
	tvTime = (TextView) findViewById(R.id.tvnewscheduleTime);
	bDone = (Button) findViewById(R.id.bxjrcDone);
	bCancel = (Button) findViewById(R.id.bxjrcCancel);
	adView = (AdView) findViewById(R.id.adView);
	adView.loadAd(request);
	etTitle.setText(schTemp.getTitle());
	etNote.setText(schTemp.getNote());
	tvDate.setText(schTemp.getDate1());
	tvTime.setText(schTemp.getTimeSet() ? schTemp.getTime1() : "全天");
	// 類型spinner設置
	spTypeAdapter = new SpTypeAdapter(context, alType);
	spType.setAdapter(spTypeAdapter);
	spType.setSelection(sel);
	spAlarmAdapter = new SpAlarmAdapter(context, alAlarm);
	spAlarm.setAdapter(spAlarmAdapter);
	spAlarm.setSelection(sel2);
	spAlarm.setOnItemSelectedListener(new OnItemSelectedListener() {

	    @Override
	    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		schTemp.setTime2(alAlarm.get(position).getValue());
		if (position > 0) {
		    schTemp.setAlarmSet(true);
		    schTemp.setTime2(alAlarm.get(position).getValue());
		} else {
		    schTemp.setAlarmSet(false);
		    schTemp.setTime2("x");
		}
	    }

	    @Override
	    public void onNothingSelected(AdapterView<?> parent) {}
	});
	bNewType.setOnClickListener(NewClickListener);
	bSetDate.setOnClickListener(NewClickListener);
	bDone.setOnClickListener(NewClickListener);
	bCancel.setOnClickListener(NewClickListener);
    }

    OnClickListener NewClickListener = new OnClickListener() {

	@Override
	public void onClick(View v) {
	    switch (v.getId()) {
		case R.id.bxjrcNewType:// 新建日程類型按鈕
		    schTemp.setTitle(etTitle.getText().toString());// 將已經輸入的title和note存入schTemp，以防返回時被清空
		    schTemp.setNote(etNote.getText().toString());
		    sel = spType.getSelectedItemPosition();// 存儲spType的當前選擇
		    sel2 = spAlarm.getSelectedItemPosition();
		    gotoTypeManager();// 進入類型管理界面
		    break;
		case R.id.bxjrcSetDate:// 設置日程日期按鈕
		    schTemp.setTitle(etTitle.getText().toString());// 將已經輸入的主題和備註存入schTemp，以防設置完時間或鬧鐘返回時被清空
		    schTemp.setNote(etNote.getText().toString());
		    sel = spType.getSelectedItemPosition();
		    sel2 = spAlarm.getSelectedItemPosition();
		    wcSetTimeOrAlarm = WhoCall.SETTING_DATE;// 調用設置日期時間對話框的是設置日程日期按鈕
		    showDialog(DIALOG_SET_DATETIME);
		    break;
		case R.id.bxjrcDone:// 完成按鈕設置，加入手機日曆操作
		    // 讓新建的日程時間和當前時間比較看是否過期
		    if (schTemp.isPassed()) {
			Toast.makeText(context, "不能創建過期日程", Toast.LENGTH_SHORT).show();
			return;
		    }
		    String title = etTitle.getText().toString().trim();
		    if (title.equals("")) {// 如果日程標題沒有輸入，默認為未命名
			title = "未命名";
		    }
		    schTemp.setTitle(title);
		    String note = etNote.getText().toString();
		    schTemp.setNote(note);
		    String type = (String) spType.getSelectedItem();
		    schTemp.setType(type);
		    if (!schTemp.getTimeSet()) {
			schTemp.setTime1("23", "59");
		    }
		    if (wcNewOrEdit == WhoCall.NEW) {// 如果當前界面是新建日程，調用插入日程方法
			insertSchedule(DmActivity.this);
		    } else if (wcNewOrEdit == WhoCall.EDIT) {// 如果當前界面是修改日程，調用更新日程方法
			updateSchedule(DmActivity.this);
		    }
		    gotoMain();
		    break;
		case R.id.bxjrcCancel:// 取消按鈕設置
		    gotoMain();
		    break;
	    }
	}
    };
    // ===================================類型管理界面start=====================================
    ListView lvType;
    EditText etNew;
    Button bNew, bBack;
    ListTypeAdapter listTypeAdapter;

    public void gotoTypeManager() {
	setContentView(R.layout.typemanager);
	context = this;
	curr = Layout.TYPE_MANAGER;
	lvType = (ListView) findViewById(R.id.lvtypemanagerType);// 列表列出所有已有類型
	etNew = (EditText) findViewById(R.id.ettypemanagerNewType);// 輸入新類型名稱的TextView
	bNew = (Button) findViewById(R.id.btypemanagerNewType);// 新建類型按鈕
	bBack = (Button) findViewById(R.id.btypemanagerBack);// 返回上一頁按鈕
	adView = (AdView) findViewById(R.id.adView);
	adView.loadAd(request);
	bNew.setOnClickListener(typeClickListener);
	bBack.setOnClickListener(typeClickListener);
	listTypeAdapter = new ListTypeAdapter(context, alType);
	lvType.setAdapter(listTypeAdapter);
	lvType.setOnItemClickListener(new OnItemClickListener() {

	    @Override
	    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
		if (position >= defultType.length) {
		    AlertDialog.Builder builder = new AlertDialog.Builder(context);
		    LayoutInflater inflater = LayoutInflater.from(context);
		    View delTypeView = inflater.inflate(R.layout.dialogdeltype, null);
		    Button bDelTypeOk = (Button) delTypeView.findViewById(R.id.bDelTypeOk);
		    Button bDelTypeCancel = (Button) delTypeView.findViewById(R.id.bDelTypeCancel);
		    bDelTypeOk.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			    deleteType(DmActivity.this, lvType.getItemAtPosition(position)
				    .toString());
			    loadType(DmActivity.this);
			    gotoTypeManager();
			    dialogDelType.cancel();
			}
		    });
		    bDelTypeCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
			    dialogDelType.cancel();
			}
		    });
		    builder.setView(delTypeView);
		    dialogDelType = builder.create();
		    dialogDelType.show();
		}
	    }
	});
    }

    OnClickListener typeClickListener = new OnClickListener() {

	@Override
	public void onClick(View v) {
	    switch (v.getId()) {
		case R.id.btypemanagerNewType:
		    String newType = etNew.getText().toString().trim();
		    if (newType.equals("")) {
			Toast.makeText(DmActivity.this, "類型名稱不能為空。", Toast.LENGTH_SHORT).show();
			return;
		    }
		    insertType(context, newType);
		    gotoTypeManager();
		    break;
		case R.id.btypemanagerBack:
		    gotoSetting();
		    break;
	    }
	}
    };
    // ===================================查找界面start========================================
    Button sChange, sSearch, sCancel;
    CheckBox cbDateRange, cbAllType;
    ListView slv;
    TextView tvFrom, tvTo;
    ArrayList<String> type;
    public static ArrayList<Boolean> alSelectedType = new ArrayList<Boolean>();// 記錄查找界面中類型前面checkbox狀態的

    public void gotoSearch() {
	setContentView(R.layout.search);
	curr = Layout.SEARCH;
	sChange = (Button) findViewById(R.id.bsearchChange);// 改變查找範圍按鈕
	sSearch = (Button) findViewById(R.id.bsearchGo);// 開始查找
	sCancel = (Button) findViewById(R.id.bsearchCancel);// 取消
	cbDateRange = (CheckBox) findViewById(R.id.cbsearchDateRange);// 查找是否限制範圍的CheckBox
	cbAllType = (CheckBox) findViewById(R.id.cbsearchType);// 是否在在所有類型中查找的CheckBox
	slv = (ListView) findViewById(R.id.lvSearchType);// 所有類型列在lv中
	tvFrom = (TextView) findViewById(R.id.tvsearchFrom);// 查找起始時期的tv
	tvTo = (TextView) findViewById(R.id.tvsearchTo);// //查找終止時期的tv
	adView = (AdView) findViewById(R.id.adView);
	adView.loadAd(request);
	tvFrom.setText(rangeFrom);
	tvTo.setText(rangeTo);
	type = getAllType(context);// 獲取已存日程中的所有類型和用戶自建的所有類型
	alSelectedType.clear();
	for (int i = 0; i < type.size(); i++) {// 默認為所有類型設置狀態位false
	    alSelectedType.add(false);
	}
	cbDateRange.setOnCheckedChangeListener(new OnCheckedChangeListener() {

	    // 根據是否限制日期範圍的CheckBox決定更改日期範圍的按鈕是否可用
	    @Override
	    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		sChange.setEnabled(isChecked);
	    }
	});
	cbAllType.setOnCheckedChangeListener(new OnCheckedChangeListener() {

	    // 設置「在全部類型中搜索」的CheckBox改變狀態時的行為
	    @Override
	    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// 選中「全部選中」後把listview裡的所有類型後面的checkbox設成選中狀態
		for (int i = 0; i < type.size(); i++) {
		    alSelectedType.set(i, isChecked);
		}
		slv.invalidateViews();// 刷新ListView??
	    }
	});
	sChange.setOnClickListener(SearchClickListener);
	sSearch.setOnClickListener(SearchClickListener);
	sCancel.setOnClickListener(SearchClickListener);
	SearchAdapter searchAdapter = new SearchAdapter(context, type);
	slv.setAdapter(searchAdapter);
    }

    OnClickListener SearchClickListener = new OnClickListener() {

	@Override
	public void onClick(View v) {
	    switch (v.getId()) {
		case R.id.bsearchChange:
		    showDialog(DIALOG_SET_SEARCH_RANGE);
		    break;
		case R.id.bsearchGo:
		    // 如果沒有一個類型被選中則提示
		    boolean tmp = false;
		    for (boolean b : alSelectedType) {
			tmp = tmp | b;
		    }
		    if (tmp == false) {
			Toast.makeText(DmActivity.this, "請至少選中一個類型", Toast.LENGTH_SHORT).show();
			return;
		    }
		    searchSchedule(context, type);
		    gotoSearchResult();
		    break;
		case R.id.bsearchCancel:
		    gotoMain();
		    break;
	    }
	}
    };
    // ===================================查找結果界面start=====================================
    ImageButton rHome, rBack;
    ListView rlv;

    public void gotoSearchResult() {// 該界面和主界面除了少了幾個按鈕其他完全一樣
	setContentView(R.layout.searchresult);
	curr = Layout.SEARCH_RESULT;
	sel = 0;
	rHome = (ImageButton) findViewById(R.id.ibsearchresultHome);
	rBack = (ImageButton) findViewById(R.id.ibsearchresultBack);
	rlv = (ListView) findViewById(R.id.lvsearchresultSchedule);
	adView = (AdView) findViewById(R.id.adView);
	adView.loadAd(request);
	// 以下是查找結果的ListView設置
	listViewAdapter = new ListViewAdapter(context, alSch, handler);
	rlv.setAdapter(listViewAdapter);
	rlv.setOnItemClickListener(new OnItemClickListener() {

	    @Override
	    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (!open) {
		    schTemp = alSch.get(position);
		    currentPosition = position;
		    open = true;
		} else if (currentPosition != position) {
		    schTemp = alSch.get(position);
		    currentPosition = position;
		    open = true;
		} else {
		    currentPosition = -1;
		    open = false;
		}
		listViewAdapter.notifyDataSetChanged();
	    }
	});
	// 添加一個回首頁功能
	// 查找日程按鈕設置
	rBack.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		gotoSearch();
	    }
	});
	rHome.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		gotoMain();
	    }
	});
    }

    // 創建對話框
    @Override
    public Dialog onCreateDialog(int id) {
	Dialog dialog = null;
	switch (id) {
	    case DIALOG_SET_SEARCH_RANGE:
		AlertDialog.Builder b = new AlertDialog.Builder(this);
		b.setItems(null, null);
		dialogSetRange = b.create();
		dialog = dialogSetRange;
		break;
	    case DIALOG_SET_DATETIME:
		AlertDialog.Builder abSetDatetime = new AlertDialog.Builder(this);
		abSetDatetime.setItems(null, null);
		dialogSetDatetime = abSetDatetime.create();
		dialog = dialogSetDatetime;
		break;
	    case DIALOG_SCH_DEL_CONFIRM:
		AlertDialog.Builder abSchDelConfirm = new AlertDialog.Builder(this);
		abSchDelConfirm.setItems(null, null);
		dialogSchDelConfirm = abSchDelConfirm.create();
		dialog = dialogSchDelConfirm;
		break;
	    case DIALOG_SCH_SYNC_CONFIRM:
		AlertDialog.Builder abSchSyncConfirm = new AlertDialog.Builder(this);
		abSchSyncConfirm.setItems(null, null);
		dialogSchSyncConfirm = abSchSyncConfirm.create();
		dialog = dialogSchSyncConfirm;
		break;
	    case DIALOG_ALL_DEL_CONFIRM:
		AlertDialog.Builder abAllDelConfirm = new AlertDialog.Builder(this);
		abAllDelConfirm.setItems(null, null);
		dialogAllDelConfirm = abAllDelConfirm.create();
		dialog = dialogAllDelConfirm;
		break;
	}
	return dialog;
    }

    // 每次彈出Dialog對話框時更新對話框的內容
    int year, month, day;
    int year1, month1, day1;
    int year2, month2, day2;
    Calendar calendar;
    public static ProgressDialog progressDialog;
    int maximum = 100;

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
	super.onPrepareDialog(id, dialog);
	switch (id) {
	    case DIALOG_SET_SEARCH_RANGE:// 設置搜索範圍對話框
		dialog.setContentView(R.layout.dialogsetrange);
		DatePicker startDate = (DatePicker) dialog.findViewById(R.id.startdate);
		DatePicker endDate = (DatePicker) dialog.findViewById(R.id.enddate);
		Button bSetRangeOk = (Button) dialog.findViewById(R.id.bdialogsetrangeOk);
		Button bSetRangeCancel = (Button) dialog.findViewById(R.id.bdialogsetrangeCancel);
		calendar = Calendar.getInstance();
		year1 = year2 = calendar.get(Calendar.YEAR);
		month1 = month2 = calendar.get(Calendar.MONTH) + 1;
		day1 = day2 = calendar.get(Calendar.DAY_OF_MONTH);
		startDate.setCalendarViewShown(false);
		endDate.setCalendarViewShown(false);
		startDate.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
			calendar.get(Calendar.DAY_OF_MONTH),
			new DatePicker.OnDateChangedListener() {

			    @Override
			    public void onDateChanged(DatePicker view, int year, int monthOfYear,
				    int dayOfMonth) {
				year1 = year;
				month1 = monthOfYear + 1; // 月的初始是0，所以先加 1。
				day1 = dayOfMonth;
			    }
			});
		endDate.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
			calendar.get(Calendar.DAY_OF_MONTH),
			new DatePicker.OnDateChangedListener() {

			    @Override
			    public void onDateChanged(DatePicker view, int year, int monthOfYear,
				    int dayOfMonth) {
				year2 = year;
				month2 = monthOfYear + 1; // 月的初始是0，所以先加 1。
				day2 = dayOfMonth;
			    }
			});
		bSetRangeOk.setOnClickListener(new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			if (day1 > getMaxDayOfMonth(year1, month1)
				|| day2 > getMaxDayOfMonth(year2, month2)) {
			    Toast.makeText(context, "日期設置錯誤", Toast.LENGTH_SHORT).show();
			    return;
			}
			rangeFrom = Schedule.toDateString(year1, month1, day1);
			rangeTo = Schedule.toDateString(year2, month2, day2);
			if (rangeFrom.compareTo(rangeTo) > 0) {
			    Toast.makeText(context, "起始日期不能大於終止日期", Toast.LENGTH_SHORT).show();
			    return;
			}
			dialogSetRange.cancel();
			gotoSearch();
		    }
		});
		// 點取消則對話框關閉
		bSetRangeCancel.setOnClickListener(new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			dialogSetRange.cancel();
		    }
		});
		break;
	    case DIALOG_SET_DATETIME:// 設置時間日期對話框
		dialog.setContentView(R.layout.dialogdatetime);
		final DatePicker datePicker = (DatePicker) dialog.findViewById(R.id.datePicker);
		final TimePicker timePicker = (TimePicker) dialog.findViewById(R.id.timePicker);
		final CheckBox cbSetTime = (CheckBox) dialog
			.findViewById(R.id.cbdialogdatetimeSettime);
		Button bSetDateOk = (Button) dialog.findViewById(R.id.bdialogdatetimeOk);
		Button bSetDateCancel = (Button) dialog.findViewById(R.id.bdialogdatetimeCancel);
		LinearLayout llCheckBox = (LinearLayout) dialog
			.findViewById(R.id.lldialogdatetimeCheckBox);
		calendar = Calendar.getInstance();
		year = calendar.get(Calendar.YEAR);
		month = calendar.get(Calendar.MONTH) + 1;
		day = calendar.get(Calendar.DAY_OF_MONTH);
		datePicker.setCalendarViewShown(false);
		datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
			calendar.get(Calendar.DAY_OF_MONTH),
			new DatePicker.OnDateChangedListener() {

			    @Override
			    public void onDateChanged(DatePicker view, int years, int monthOfYear,
				    int dayOfMonth) {
				year = years;
				month = monthOfYear + 1;
				day = dayOfMonth;
			    }
			});
		timePicker.setOnTimeChangedListener(new OnTimeChangedListener() {

		    @Override
		    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {}
		});
		timePicker.setIs24HourView(true);// 是否顯示24小時制？默認false
		// 如果是設置日期按鈕調用的本對話框
		if (wcSetTimeOrAlarm == WhoCall.SETTING_DATE) {
		    llCheckBox.setVisibility(View.VISIBLE);// 是否設置具體時間的CheckBox顯示出來
		    // llAlarmCheckBox.setVisibility(View.GONE);// 是否設置鬧鐘的CheckBox不顯示
		    // 把schTemp中的year month day顯示在EditText中
		    datePicker.updateDate(schTemp.getYear(), schTemp.getMonth() - 1,
			    schTemp.getDay());
		    // 如果schTemp中表示是否設置具體時間的布爾值timeSet為true，即設置了具體時間，則把已設置的時分顯示在EditText中
		    if (schTemp.getTimeSet()) {
			timePicker.setCurrentHour(schTemp.getHour());
			timePicker.setCurrentMinute(schTemp.getMinute());
		    } else// 否則默認顯示八點
		    {
			timePicker.setCurrentHour(8);
			timePicker.setCurrentMinute(0);
		    }
		    // 是否設置具體時間的CheckBox決定有關設置時間的控件可不可用
		    cbSetTime.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			    timePicker.setEnabled(isChecked);
			}
		    });
		    // 這三條語句確保觸發cbSetTime的OnCheckedChangeListener
		    cbSetTime.setChecked(schTemp.getTimeSet());
		    cbSetTime.setChecked(!schTemp.getTimeSet());
		    cbSetTime.setChecked(schTemp.getTimeSet());
		}
		bSetDateOk.setOnClickListener(new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			int y = datePicker.getYear();
			int m = datePicker.getMonth() + 1;
			int d = datePicker.getDayOfMonth();
			int h = timePicker.getCurrentHour();
			int mm = timePicker.getCurrentMinute();
			String year = String.valueOf(y);
			String month = String.valueOf(m < 10 ? "0" + m : m);
			String day = String.valueOf(d < 10 ? "0" + d : d);
			// 最後再檢查一下是否有年月日設置錯誤，比如2月30號等等
			if (d > getMaxDayOfMonth(y, m)) {
			    Toast.makeText(DmActivity.this, "日期設置錯誤", Toast.LENGTH_SHORT).show();
			    return;
			}
			// 如果此對話框是被設置日期按鈕調用的，把年月日賦給Schedule中的Date1，即日程日期
			if (wcSetTimeOrAlarm == WhoCall.SETTING_DATE) {
			    schTemp.setDate1(year, month, day);
			    schTemp.setTimeSet(cbSetTime.isChecked());
			    if (cbSetTime.isChecked())// 如果設置了具體時間，把時分賦給Schedule中的Time1，即日程時間
			    {
				String hour = String.valueOf(h < 10 ? "0" + h : h);
				String min = String.valueOf(mm < 10 ? "0" + mm : mm);
				schTemp.setTime1(hour, min);
			    }
			}
			dialogSetDatetime.cancel();
			gotoSetting();
		    }
		});
		bSetDateCancel.setOnClickListener(new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			dialogSetDatetime.cancel();
		    }
		});
		break;
	    case DIALOG_SCH_DEL_CONFIRM:// 刪除日程對話框
		dialog.setContentView(R.layout.dialogschdelconfirm);
		Button bDelOk = (Button) dialog.findViewById(R.id.bdialogschdelconfirmOk);
		Button bDelCancel = (Button) dialog.findViewById(R.id.bdialogschdelconfirmCancel);
		bDelOk.setOnClickListener(new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			int id = schTemp.getEvent_id();
			deleteSchedule(DmActivity.this, id);
			gotoMain();
			dialogSchDelConfirm.cancel();
		    }
		});
		bDelCancel.setOnClickListener(new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			dialogSchDelConfirm.cancel();
		    }
		});
		break;
	    case DIALOG_SCH_SYNC_CONFIRM:// 同步日程對話框
		dialog.setContentView(R.layout.dialogschsyncconfirm);
		Button syncOk = (Button) dialog.findViewById(R.id.sdialogschsyncconfirmOk);
		Button syncCancel = (Button) dialog.findViewById(R.id.sdialogschsyncconfirmCancel);
		final CheckBox ckpassOK = (CheckBox) dialog.findViewById(R.id.passOK);
		ckpassOK.setChecked(false);
		alEventId.clear();
		EventIdList = getAllEventId(context);
		syncOk.setOnClickListener(new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			dialogSchSyncConfirm.cancel();
			progressDialog = new ProgressDialog(context);
			progressDialog.setCancelable(false);
			progressDialog.setMessage("同步中，請稍後...");
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressDialog.setProgress(0);
			progressDialog.setMax(maximum);
			progressDialog.show();
			new createProDialog(ckpassOK.isChecked()).start();
		    }
		});
		syncCancel.setOnClickListener(new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			dialogSchSyncConfirm.cancel();
		    }
		});
		break;
	    case DIALOG_ALL_DEL_CONFIRM:// 刪除所有過期日程對話框
		dialog.setContentView(R.layout.dialogdelpassedconfirm);
		Button bAllDelOk = (Button) dialog.findViewById(R.id.bdialogdelpassedconfirmOk);
		Button bAllDelCancel = (Button) dialog
			.findViewById(R.id.bdialogdelpassedconfirmCancel);
		bAllDelOk.setOnClickListener(new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			deletePassedSchedule(context);
			gotoMain();
			dialogAllDelConfirm.cancel();
		    }
		});
		bAllDelCancel.setOnClickListener(new OnClickListener() {

		    @Override
		    public void onClick(View v) {
			dialogAllDelConfirm.cancel();
		    }
		});
		break;
	}
    }

    private class createProDialog extends Thread {

	private boolean check;

	public createProDialog(boolean check) {
	    this.check = check;
	}

	public void run() {
	    util.syncEvent(EventIdList);
	    if (!check) {
		handler.sendEmptyMessage(3);
	    } else {
		handler.sendEmptyMessage(4);
	    }
	    progressDialog.cancel();
	};
    };

    // onKeyDown方法
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
	// 按下手機返回按鈕時
	if (keyCode == 4) {
	    switch (curr) {
		case MAIN:// 在主界面的話退出程序
		    System.exit(0);
		    break;
		case SETTING:// 在日程編輯界面的話返回主界面
		    gotoMain();
		    break;
		case TYPE_MANAGER:// //在類型管理界面的話返回日程編輯界面
		    gotoSetting();
		    break;
		case SEARCH:// 在日程查找界面的話返回主界面
		    gotoMain();
		    break;
		case SEARCH_RESULT:// 在日程查找結果界面的話返回日程查找界面
		    gotoSearch();
		    break;
	    }
	    return true;
	}
	return false;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
	return super.onMenuItemSelected(featureId, item);
    }

    // 用來得到year年month月的最大天數
    public int getMaxDayOfMonth(int year, int month) {
	int day = 0;
	boolean run = false;
	if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0) {
	    run = true;
	}
	if (month == 4 || month == 6 || month == 9 || month == 11) {
	    day = 30;
	} else if (month == 2) {
	    if (run) {
		day = 29;
	    } else {
		day = 28;
	    }
	} else {
	    day = 31;
	}
	return day;
    }

    // 返回把YYYY/MM/DD分隔後的年月日字符串數組
    public String[] splitYMD(String ss) {
	String[] s = ss.split("/");
	return s;
    }
}
